<template>
  <el-dialog v-model="visible" :title="title" width="80%" destroy-on-close>
    <!-- 基础信息 -->
    <el-form :model="formData" ref="formRef" label-width="120px" :rules="rules">
      <h4>基础信息</h4>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物流公司名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物流公司分类" prop="logisticsClass">
            <el-select v-model="formData.logisticsClass" placeholder="请选择">
              <el-option v-for="item in props.logisticsClassOptions" :key="item" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="经营范围" prop="scope">
            <el-input v-model="formData.scope" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司规模" prop="scale">
            <el-input v-model="formData.scale" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="公司邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="公司传真" prop="fax">
            <el-input v-model="formData.fax" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司网站" prop="website">
            <el-input v-model="formData.website" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 联系人表格 -->
    <div style="margin-top:20px;">
      <h4>联系人</h4>
      <div style="margin-bottom:10px; margin-top: 10px;">
        <el-button type="primary" @click="openContactDialog('create')">新增</el-button>
        <el-button plain class="blue-btn" @click="openContactDialog('edit')">编辑</el-button>
        <el-button plain class="blue-btn red-hover"  @click="removeContacts">删除</el-button>
      </div>
      <!-- ✅ 滚动容器 -->
      <div style="overflow-x: auto; max-width: 100%; padding-bottom: 8px;">
        <el-table
          :data="formData.contacts"
          @selection-change="onContactSelectionChange" border
          style="min-width: auto; white-space: nowrap;"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="联系人" min-width="120" />
          <el-table-column prop="sex" label="性别" min-width="80" />
          <el-table-column prop="position" label="职务" min-width="150" />
          <el-table-column prop="email" label="邮箱" min-width="200" />
          <el-table-column prop="landline" label="座机" min-width="150" />
          <el-table-column prop="phone" label="移动电话" min-width="180" />
          <el-table-column prop="facebook" label="Facebook" min-width="200" />
          <el-table-column prop="ins" label="ins" min-width="200" />
          <el-table-column prop="tiktok" label="TikTok" min-width="200" />
          <el-table-column prop="youtube" label="Youtube" min-width="200" />
          <el-table-column prop="linkedin" label="Linkedin" min-width="200" />
          <el-table-column prop="remark" label="备注" min-width="600" />
        </el-table>
      </div>
    </div>

    <!-- 弹窗底部按钮 -->
    <template #footer>
      <div style="display: flex; justify-content: center; gap: 12px; width: 100%;">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </template>

    <!-- 联系人编辑弹窗 -->
    <el-dialog v-model="contactVisible" :title="contactDialogTitle" width="40%">
      <el-form :model="contactForm" ref="contactFormRef" label-width="100px" :rules="contactRules">        
        <el-form-item label="姓名" prop="name"> <el-input v-model="contactForm.name"/> </el-form-item>
        <el-form-item label="性别"> <el-input v-model="contactForm.sex"/> </el-form-item>
        <el-form-item label="职务"> <el-input v-model="contactForm.position"/> </el-form-item>
        <el-form-item label="邮箱"> <el-input v-model="contactForm.email"/> </el-form-item>
        <el-form-item label="座机"> <el-input v-model="contactForm.landline"/> </el-form-item>
        <el-form-item label="移动电话" prop="phone"> <el-input v-model="contactForm.phone"/> </el-form-item>
        <el-form-item label="Facebook"> <el-input v-model="contactForm.facebook"/> </el-form-item>
        <el-form-item label="ins"> <el-input v-model="contactForm.ins"/> </el-form-item>
        <el-form-item label="TikTok"> <el-input v-model="contactForm.tiktok"/> </el-form-item>
        <el-form-item label="youtube"> <el-input v-model="contactForm.youtube"/> </el-form-item>
        <el-form-item label="linkedin"> <el-input v-model="contactForm.linkedin"/> </el-form-item>
        <el-form-item label="备注"> <el-input v-model="contactForm.remark"/> </el-form-item>
      </el-form>

      <template #footer>
        <div style="display: flex; justify-content: center; gap: 12px; width: 100%;">
          <el-button @click="contactVisible = false">取消</el-button>
          <el-button type="primary" @click="saveContact">保存</el-button>
        </div>
    </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { LogistCompanyApi } from '@/api/busipart/logistcompany'

defineOptions({ name: 'LogistCompanyForm' })

const visible = ref(false)
const title = ref('')
const formRef = ref()

// 打开主表单
const open = (type: string, data?: any) => {
  visible.value = true
  title.value = type === 'create' ? '新增物流公司' : '编辑物流公司'
  if (type === 'edit' && data) {
    Object.assign(formData, data)
  } else {
    Object.assign(formData, {
      id: null,
      name: '',
      logisticsClass: '',
      scope: '',
      scale: '',
      email: '',
      phone: '',
      fax: '',
      website: '',
      remark: '',
      contacts: []
    })
  }
}

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  logisticsClass: '',
  scope: '',
  scale: '',
  email: '',
  phone: '',
  fax: '',
  website: '',
  remark: '',
  contacts: []
})

// 物流公司表单校验规则
const rules = {
  name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  logisticsClass: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

// 联系人表单验证规则
const contactRules = {
  name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入移动电话', trigger: 'blur' }]
}

// 下拉选项
const props = defineProps({
  // 接收父组件传递的物流分类下拉数据
  logisticsClassOptions: {
    type: Array as () => string[], // 类型为字符串数组
    default: () => [] // 默认值为空数组
  }
})

// 联系人选择
const selectedContacts = ref([])

const contactVisible = ref(false)
const contactFormRef = ref()
const contactForm = reactive({
  name: '',
  sex: '',
  position: '',
  email: '',
  landline: '',
  phone: '',
  facebook: '',
  ins: '',
  tiktok: '',
  youtube: '',
  linkedin: '',
  remark: ''
})
const contactDialogTitle = ref('')


// 联系人相关
const onContactSelectionChange = (rows: any[]) => {
  selectedContacts.value = rows
}

const openContactDialog = (type: string) => {
  if (type === 'edit' && selectedContacts.value.length !== 1) {
    ElMessage.warning('请选择一个联系人进行编辑')
    return
  }
  contactDialogTitle.value = type === 'create' ? '新增联系人' : '编辑联系人'
  contactVisible.value = true
  if (type === 'edit') {
    Object.assign(contactForm, selectedContacts.value[0])
  } else {
    Object.assign(contactForm, { 
      name: '', sex: '', position: '', email: '', phone: '', fax: '', landline: '',
      facebook: '', ins: '', tiktok: '', youtube: '', linkedin: '',remark: '' })
  }
}

const saveContact = () => {
  contactFormRef.value.validate((valid: boolean) => {
    if (!valid) return
    if (contactDialogTitle.value.includes('新增')) {
      formData.contacts.push({ ...contactForm, id: null }) // 确保新增时id为空
    } else {
      const index = formData.contacts.findIndex(c => c === selectedContacts.value[0])
      if (index !== -1) formData.contacts[index] = { ...contactForm }
    }
    contactVisible.value = false
    ElMessage.success('联系人已添加到列表')
  })
}


const removeContacts = () => {
  if (selectedContacts.value.length === 0) {
    ElMessage.warning('请选择要删除的联系人')
    return
  }
  formData.contacts = formData.contacts.filter(c => !selectedContacts.value.includes(c))
  selectedContacts.value = []
}

// 提交表单
const emit = defineEmits(['success']) // 添加 emit

const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    try {
      if (formData.id) {
        await LogistCompanyApi.updateLogistCompany(formData)
        ElMessage.success('更新成功')
      } else {
        await LogistCompanyApi.createLogistCompany(formData)
        ElMessage.success('新增成功')
      }
      visible.value = false
      emit('success') // 通知父组件刷新列表
    } catch (error) {
      ElMessage.error('保存失败，请稍后再试')
    }
  })
}

// 暴露方法给父组件
defineExpose({ open })
</script>

<style scoped>

.blue-btn {
  border: 1px solid #409eff;
  color: #409eff;
  background-color: white;
  transition: all 0.3s ease;
}

.blue-btn:hover {
  background-color: #409eff;
  color: white;
}

.red-hover {
  border-color: #409eff;
  color: #409eff;
  background-color: white;
  transition: all 0.3s ease;
}

.red-hover:hover {
  background-color: #ff4d4f;
  color: white;
  border-color: #ff4d4f;
}
</style>